package com.apps.globals.advent.service.impl;

import com.alibaba.fastjson.JSON;
import com.apps.common.enums.ClientType;
import com.apps.globals.advent.model.po.KupaAdvent;
import com.apps.globals.advent.dao.KupaAdventMapper;
import com.apps.globals.advent.model.vo.KupaAdventVo;
import com.apps.globals.advent.service.IKupaAdventService;
import com.apps.goods.model.po.KupaGoodsCat;
import com.apps.goods.model.vo.KupaGoodsCatVo;
import com.apps.sannotation.service.OnRedisCache;
import com.apps.sannotation.service.enums.CacheModel;
import com.apps.sexctption.DataException;
import com.apps.sexctption.NullException;
import com.apps.sutils.StringUtils;
import com.apps.sworld.dao.impl.sDaoImpl;

import com.apps.thirdparty.upload.fileupload.config.IKupaUpLoadConfig;
import com.apps.thirdparty.upload.fileupload.service.IKupaFileUploadService;
import com.apps.thirdparty.upload.fileupload.utils.KupaFileUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 大鹏
 * @since 2020-10-02
 */
@Slf4j
@OnRedisCache(model = CacheModel.ALL)
@Service
public class KupaAdventServiceImpl extends sDaoImpl<KupaAdventMapper, KupaAdvent> implements IKupaAdventService
{
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private IKupaFileUploadService fileUploadService;

    @Autowired
    private IKupaUpLoadConfig upLoadConfig;

    @Override
    public void addAdvent(String name, String key, float width_height_rate, ClientType clientType)
    {
        KupaAdvent advent=new KupaAdvent();
        advent.setName(name);
        advent.setProd_key(key);
        advent.setWidth_height_rate(width_height_rate);
        advent.setKey_value(JSON.toJSONString(new ArrayList<KupaAdventVo>()));
        advent.setClient(clientType.name());
        saveToDB(advent);
    }

    @Override
    public List<KupaAdventVo> getOneAdventById(int id)
    {
        KupaAdvent advent= getOneById(id);
        if(null==advent)
            throw new DataException("广告位不存在");
        if(!StringUtils.isNotEmpty(advent.getKey_value()))
            throw new DataException("广告数据异常");

        return JSON.parseArray(advent.getKey_value(),KupaAdventVo.class);
    }

    @Override
    public List<KupaAdventVo> getOneAdventByKey(String key)
    {
        KupaAdvent advent= getOneByFieldValue("prod_key",key);
        if(null==advent)
            throw new DataException("广告位不存在");
        if(!StringUtils.isNotEmpty(advent.getKey_value()))
            throw new DataException("广告数据异常");

        return JSON.parseArray(advent.getKey_value(),KupaAdventVo.class);
    }

    @SneakyThrows
    @Override
    public List<KupaAdventVo> addAdventItem(int id, String name, MultipartFile img, String url)
    {
            KupaAdvent advent=getOneById(id);
            if(null==advent)
                throw new DataException("广告位不存在");
            if(!KupaFileUtils.verifyImagesRate(img,advent.getWidth_height_rate()))
                throw new DataException("图片尺寸不合格,宽高比必须为:"+advent.getWidth_height_rate());
            if(!StringUtils.isNotEmpty(advent.getKey_value()))
                throw new DataException("广告数据异常");
            List<KupaAdventVo> banner=JSON.parseArray(advent.getKey_value(),KupaAdventVo.class);
            //上传文件
            String fileName=fileUploadService.saveToWebp(img,upLoadConfig.getImages());
            banner.add(new KupaAdventVo(name,fileName,url));
            advent.setKey_value(JSON.toJSONString(banner));
            updateById(advent);
            return banner;
    }

    @Override
    public List<KupaAdventVo> delAdventItem(int id, int index)
    {
        KupaAdvent advent=getOneById(id);
        if(null==advent)
            throw new DataException("广告位不存在");
        if(!StringUtils.isNotEmpty(advent.getKey_value()))
            throw new DataException("广告数据异常");
        List<KupaAdventVo> banner=JSON.parseArray(advent.getKey_value(),KupaAdventVo.class);
        if(index>=banner.size())
            throw new DataException("传入的广告排序参数溢出");
        banner.remove(index);
        advent.setKey_value(JSON.toJSONString(banner));
        updateById(advent);
        return banner;
    }

    @Override
    public List<KupaAdventVo> queryAdventItem(int adventId)
    {
        KupaAdvent advent=getOneById(adventId);
        if(null==advent)
            throw new DataException("广告位不存在");
        if(!StringUtils.isNotEmpty(advent.getKey_value()))
            throw new DataException("广告数据异常");
        return JSON.parseArray(advent.getKey_value(),KupaAdventVo.class);
    }

    @SneakyThrows
    @Override
    public List<KupaAdventVo> updateAdventItemById(int id, int index, String name, MultipartFile img, String url)
    {
        KupaAdvent advent=getOneById(id);
        if(null==advent)
            throw new DataException("广告位"+id+"不存在");

        if(!StringUtils.isNotEmpty(advent.getKey_value()))
            throw new NullException("广告数据异常");
        List<KupaAdventVo> banner=JSON.parseArray(advent.getKey_value(),KupaAdventVo.class);
        if(index>=banner.size())
            throw new DataException("传入的广告排序参数溢出");
        //如果有图片则上传文件
        if(null!=img)
        {
            if(!KupaFileUtils.verifyImagesRate(img,advent.getWidth_height_rate()))
                throw new DataException("图片尺寸不合格,宽高比必须为"+advent.getWidth_height_rate());
            String fileName=fileUploadService.save(img,upLoadConfig.getImages());
            banner.set(index, new KupaAdventVo(name,fileName, url));
            advent.setKey_value(JSON.toJSONString(banner));
        }
        updateById(advent);
        return banner;
    }

    @Override
    public Map<String, KupaAdventVo> QueryMap()
    {
        return (Map<String, KupaAdventVo>) redisTemplate.opsForValue().get(this.getClass().getSimpleName()+this.currentModelClass().getSimpleName());
    }

    /**
     * 将所有广告数据压入redis
     */
    private void QueryAndCacheMasterData()
    {
        List<KupaAdvent> advents=query();
        Map<String, List<KupaAdventVo>> result=new HashMap<>();
        for(KupaAdvent advent : advents)
            result.put(advent.getProd_key(), JSON.parseArray(advent.getKey_value(),KupaAdventVo.class));
        redisTemplate.opsForValue().set(this.getClass().getSimpleName()+this.currentModelClass().getSimpleName(),result);
    }

    @Override
    public void onLoad()
    {
        //将所有一级分类加载到缓存
        QueryAndCacheMasterData();
    }
    @Override
    public void onCreate(KupaAdvent advent)
    {
        //将所有一级分类加载到缓存
        QueryAndCacheMasterData();
    }

    @Override
    public void onUpdate(KupaAdvent advent)
    {
        //将所有一级分类加载到缓存
        QueryAndCacheMasterData();
    }

    @Override
    public void onDelete(List<KupaAdvent> advents)
    {
        //将所有一级分类加载到缓存
        QueryAndCacheMasterData();
    }

}
